package com.zz.webapp.service.impl;
import com.alibaba.fastjson.JSON;
import com.zz.webapp.common.Response.Response;
import com.zz.webapp.dao.UserDao;
import com.zz.webapp.dto.UserDto;
import com.zz.webapp.enums.ErrorCode;
import com.zz.webapp.manager.UserManager;
import com.zz.webapp.model.User;
import com.zz.webapp.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
	public static final Logger logger = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserManager userManager;

	public User getUserById(Long userId) {
		return userDao.load(userId);
	}

	public Response<User> login(String userName, String password) {
		logger.info("ssm[] UserServiceImpl[] login:userName:"+JSON.toJSONString(userName)+",password:"+JSON.toJSONString(password));
		if(null == userName || null == password){
			return Response.fail(ErrorCode.PARAM_INVALID.toString());
		}
		try {
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("userName",userName);
			map.put("password",password);
			List<User> list = userDao.list(map);
			if(null == list || 0 == list.size()){
				logger.error("ssm[] UserServiceImpl[] login:account is not exist !");
				return Response.fail(ErrorCode.ACCOUNT_NOT_EXIST.toString());
			}
			if(1 < list.size()){
				logger.error("ssm[] UserServiceImpl[] login:account is exception !");
				return Response.fail(ErrorCode.ACCOUNT_EXCEPTION.toString());
			}
			logger.info("ssm[] UserServiceImpl[] login:list:"+ JSON.toJSONString(list));
			User user = list.get(0);
			return Response.ok(user);
		}catch (Exception e){
			logger.error("ssm[] UserServiceImpl[] login:userName:"
					+JSON.toJSONString(userName)+
					",password:"+JSON.toJSONString(password)+"case:"+e.getMessage());
			return Response.fail(ErrorCode.FAILED_LOGIN.toString());
		}
	}

	public Response<Boolean> createUser(UserDto userDto) {
		logger.info("ssm[] UserServiceImpl[] createUser:userDto:" +JSON.toJSONString(userDto));
		if(null == userDto|| null == userDto.getUserName()||null == userDto.getPassword()){
			return Response.fail(ErrorCode.PARAM_INVALID.toString());
		}
		try {
			userManager.createUser(userDto);
			return Response.ok(Boolean.TRUE);
		}catch (Exception e){
			logger.error("ssm[] UserServiceImpl[] createUser:userDto:" +JSON.toJSONString(userDto)+ "case:"+e.getMessage());
			return Response.fail(ErrorCode.CREATE_USER_FAILED.toString());
		}
	}


}
